package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetMealService setMealService;

    @Reference
    private ReportService reportService;

    //会员数量折线图数据
    @RequestMapping("getMemberReport")
    public Result getMemberReport() throws Exception {
        try {
            Map<String, Object> map = new HashMap<>();
            ArrayList<String> months = new ArrayList<>();

//        获取日历对象
            Calendar calendar = Calendar.getInstance();
//        时间倒退到12个月前
            calendar.add(Calendar.MONTH, -12);
//        在十二个月前的基础上每次加1个月
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                Date date = calendar.getTime();
                String dateStr = new SimpleDateFormat("yyyy.MM").format(date);
                months.add(dateStr);
            }
//       将十二个月的日期存入months集合
            map.put("months", months);

            List<Integer> memberCount = memberService.findMemberCountByMonths(months);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

    }
    //获取套餐预约数据
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            HashMap<String, Object> map = setMealService.findOrderCount();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }
    //获取运营数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据报表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request,HttpServletResponse response){
        try {
            //查询数据库获取所有的运营数据
            Map<String, Object> data = reportService.getBusinessReportData();
            String reportDate = (String)data.get("reportDate");
            Integer todayNewMember = (Integer) data.get("todayNewMember");
            Integer totalMember = (Integer) data.get("totalMember");
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            List<HashMap<String,Object>> hotSetmeal = (List) data.get("hotSetmeal");
            //使用poi框架操作excel模板插入数据
//            String templatePath ="D:\\IdeaProjects\\itcast_health\\health_parent\\health_backend\\src\\main\\webapp\\template\\report_template.xlsx";
            String templatePath = request.getSession().getServletContext().getRealPath("template/report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(templatePath);
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFCell cell1 = sheet.getRow(2).getCell(5);
            cell1.setCellValue(reportDate);
            XSSFCell cell2 = sheet.getRow(4).getCell(5);
            cell2.setCellValue(todayNewMember);
            XSSFCell cell3 = sheet.getRow(4).getCell(7);
            cell3.setCellValue(totalMember);
            XSSFCell cell4 = sheet.getRow(5).getCell(5);
            cell4.setCellValue(thisWeekNewMember);
            XSSFCell cell5 = sheet.getRow(5).getCell(7);
            cell5.setCellValue(thisMonthNewMember);
            XSSFCell cell6 = sheet.getRow(7).getCell(5);
            cell6.setCellValue(todayOrderNumber);
            XSSFCell cell7 = sheet.getRow(7).getCell(7);
            cell7.setCellValue(todayVisitsNumber);
            XSSFCell cell8 = sheet.getRow(8).getCell(5);
            cell8.setCellValue(thisWeekOrderNumber);
            XSSFCell cell9 = sheet.getRow(8).getCell(7);
            cell9.setCellValue(thisWeekVisitsNumber);
            XSSFCell cell10 = sheet.getRow(9).getCell(5);
            cell10.setCellValue(thisMonthOrderNumber);
            XSSFCell cell11 = sheet.getRow(9).getCell(7);
            cell11.setCellValue(thisMonthVisitsNumber);

            int hotSetmealRow=12;
            for (Map map : hotSetmeal) {
                String name = (String)map.get("name");
                String setmeal_count = map.get("setmeal_count").toString();
                String proportion = map.get("proportion").toString();
                sheet.getRow(hotSetmealRow).getCell(4).setCellValue(name);
                sheet.getRow(hotSetmealRow).getCell(5).setCellValue(setmeal_count);
                sheet.getRow(hotSetmealRow).getCell(6).setCellValue(proportion);
                hotSetmealRow++;
            }
            //将文件输出到页面上
            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream outputStream = response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename=report.xlsx");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据报表
    @RequestMapping("/exportPDF")
    public Result exportPDF(HttpServletRequest request,HttpServletResponse response){
        try {
            //jrxml和jasper文件路径
            String jrxmlPath = "D:\\IdeaProjects\\itcast_health\\health_parent\\health_backend\\src\\main\\resources\\health_business3.jrxml";
            String jasperPath = "D:\\IdeaProjects\\itcast_health\\health_parent\\health_backend\\src\\main\\resources\\health_business3.jasper";
            //编译
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //查询数据库获取所有的运营数据
            Map<String, Object> data = reportService.getBusinessReportData();
//            String reportDate = (String)data.get("reportDate");
//            Integer todayNewMember = (Integer) data.get("todayNewMember");
//            Integer totalMember = (Integer) data.get("totalMember");
//            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
//            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
//            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
//            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
//            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
//            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
//            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
//            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            List<HashMap<String,Object>> hotSetmeal = (List) data.get("hotSetmeal");


            //填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,data,new JRBeanCollectionDataSource(hotSetmeal));

            //生成pdf并将文件输出到页面上
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition","attachment;filename=report.pdf");
            ServletOutputStream outputStream = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
